#include "updatehistory.h"

#include <QHeaderView>
#include <QGridLayout>


#include <QSqlRecord>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QSqlError>
#include <QDate>

#include "../settings.h"
#include "../service.h"
#include "../definitions.h"

#include "../components/smartdelegate.h"

UpdateHistory::UpdateHistory(QWidget *parent) :
    FormInterface(parent)
{
    QSettings *settings = Settings::getInstance();
    QSettings *userSettings = Settings::getUserInstance();

    QGridLayout *mainLayout = new QGridLayout(this);

    model = new QSqlQueryModel(this);
    model->setQuery(settings->value("queries/pricehistory/get_history").toString());
    model->setHeaderData(0, Qt::Horizontal, "Артикул");
    model->setHeaderData(1, Qt::Horizontal, "Название");
    model->setHeaderData(2, Qt::Horizontal, "Дата");
    model->setHeaderData(3, Qt::Horizontal, "Цена");

    view = new QTableView(this);
    view->setModel(model);

    SmartDelegate *dgsum = new SmartDelegate(this);
    dgsum->setPrecision(2);
    dgsum->setReadOnly();
    view->setItemDelegateForColumn(3, dgsum);

    QHeaderView *header = view->verticalHeader();
    header->setDefaultSectionSize(settings->value("globals/table_height").toInt());
    header->setVisible(false);

    header = view->horizontalHeader();
    header->setStretchLastSection(true);
    //  view->horizontalHeader()->setVisible(false);

    view->setFocusPolicy(Qt::NoFocus);

    mainLayout->addWidget(view,0,0);

    int size= userSettings->beginReadArray("updatehistory/preferences/table");
    for(int i=0;i<size;++i){
        userSettings->setArrayIndex(i);
        view->setColumnWidth(i, userSettings->value("width",50).toInt());
    }
    userSettings->endArray();

}

UpdateHistory::~UpdateHistory(){
    QSettings *userSettings = Settings::getUserInstance();

    userSettings->beginWriteArray("updatehistory/preferences/table");
    for(int i=0;i<model->columnCount();++i){
        userSettings->setArrayIndex(i);
        userSettings->setValue("width", view->columnWidth(i));
    }
    userSettings->endArray();
}
